<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <title>ol6加载百度在线地图</title>
    <script src='../lib/projzh/index.min.js'></script>
    <!--    <script src='https://cdn.jsdelivr.net/npm/ol@v8.2.0/dist/ol.js'></script>-->
    <script src='../lib/ol6.15.1/ol.js'></script>
    <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/ol@v8.2.0/ol.css'>

    <style>
        html, body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        #map {
            width: 100%;
            height: 100%;
            margin: 0;
        }
    </style>
</head>
<body>
<div id='map'></div>
</body>
<script>
	// const bd09Extent = [-20037726.37, -12474104.17, 20037726.37, 16474104.17];
	const bd09Extent = [-20037726.37, -11708041.66, 20037726.37, 12474104.17];

	const getBD09ProjByCode = (projCode) => {
		let projection = ol.proj.get(projCode);
		if (projection) {
			return projection;
		}
		let projBD09 = new ol.proj.Projection({
			code: 'BD:09',
			// extent: bd09Extent,
			units: 'm',
			axisOrientation: 'neu',
			global: false
		});
		ol.proj.addProjection(projBD09);
	};
	getBD09ProjByCode('BD:09');
	let rlProject = [];
	let matrixIds = [];
	for (let i = 0; i <= 19; ++i) {
		rlProject[i] = Math.pow(2, 18 - i);
		matrixIds[i] = i;
	}
	let _tileGrid = new ol.tilegrid.TileGrid({
		origin: [0, 0],
		resolutions: rlProject,
		matrixIds: matrixIds
	});
	const baiduSource = new ol.source.TileImage({
		projection: 'BD:09',
		tileGrid: _tileGrid,
		tilePixelRatio: 2,
		wrapX: true,
		tileUrlFunction: (tileCoord, pixelRatio, proj) => {
			if (!tileCoord) {
				return '';
			}
			let z = tileCoord[0];
			let x = tileCoord[1];
			// openlayers3中加载地图的方式是右上递增，
			// openlayers6中是右下递增，所以y的值需要取负减一
			let y = -tileCoord[2] - 1;
			// 百度瓦片服务url将负数使用M前缀来标识
			if (x < 0) {
				x = 'M' + (-x);
			}
			if (y < 0) {
				y = 'M' + (-y);
			}
			return `http://maponline${Math.round(Math.random() * 3)}.bdimg.com/tile/?qt=vtile&x=${x}&y=${y}&z=${z}&styles=pl&udt=20210407&scaler=1&p=1`;
			// return `http://maponline{0-3}.bdimg.com/tile/?qt=vtile&x=${x}&y=${y}&z=${z}&styles=pl&udt=20210407&scaler=1&p=1`;
		}
	});

	const baidu = new ol.layer.Tile({
		source: baiduSource
	});

	const view = new ol.View({
		// constrainOnlyCenter: false,
		// constrainResolution: true,
		center: ol.proj.transform([121.48918852071861, 31.23421977234498], 'EPSG:4326', 'BD:09'),
		zoom: 5,
		projection: 'BD:09',
		minZoom: 4,
		// extent: bd09Extent,
		// maxResolution: rlProject[4],
		// minResolution: rlProject[19],
		resolutions: rlProject
	});
	console.log(ol.interaction.defaults);
	const map = new ol.Map({
		target: 'map',
		layers: [baidu],
		view,
		interactions: ol.interaction.defaults().extend([
			new ol.interaction.MouseWheelZoom({
				handleEvent: (event) => {
					if (event.type === 'wheel') {
						console.log(event.originalEvent.deltaY);
						let delta = event.originalEvent.deltaY > 0 ? 1 : -1;
						let currentResolution = map.getView().getResolution();
						let newResolution = currentResolution * Math.pow(2, delta);
						map.getView().setResolution(newResolution);
						event.preventDefault();
						return false;
					}
					return true;
				}
			})
		])
	});

	console.log(rlProject, map.getView().getResolution(), map.getView().getZoom());

	/*const tileGrid = new ol.tilegrid.TileGrid({
        origin: [0, 0],
        resolutions: resolutions
    });

    const baiduSource = new ol.source.TileImage({
        projection: 'BD:09',
        tileGrid: tileGrid,
        tileUrlFunction: (tileCoord) => {
            let [z, x, y] = tileCoord;
            y = -1 - y;
            // y = -y - 1;
            // 百度瓦片服务url将负数使用M前缀来标识
            // return `http://shangetu1.map.bdimg.com/it/u=x=${x};y=${y};z=${z};v=009;type=sate&fm=46&udt=20210407`;
            return `http://maponline0.bdimg.com/tile/?qt=vtile&x=${x}&y=${y}&z=${z}&styles=pl&udt=20210407`;
            // return `http://maponline0.bdimg.com/tile/?qt=vtile&x=${x}&y=${y}&z=${z}&styles=sl&udt=20210407`;
        }
    });
    // 百度地图层
    const baiduMapLayer = new ol.layer.Tile({
        source: baiduSource
    });

    const centerPoint = [116.384722, 39.889916]; // 邢台 - [114.507435,37.074612] ; 北京 - [116.384722, 39.889916]

    const circlePoint = gcoord.transform(centerPoint, gcoord.WGS84, gcoord.BD09MC);//ol.proj.transform(centerPoint, 'EPSG:4326', 'BD:09');
    console.log(circlePoint);

    const iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(circlePoint)
    });

    const iconStyle = new ol.style.Style({
        image: new ol.style.Icon(
            /!** @type {olx.style.IconOptions} *!/ ({
                anchor: [10, 26],
                anchorXUnits: 'pixels',
                anchorYUnits: 'pixels',
                src: '../image/position_orange.png'
            })
        )
    });

    iconFeature.setStyle(iconStyle);

    const vectorSource = new ol.source.Vector({
        features: [iconFeature]
    });

    const iconLayer = new ol.layer.Vector({
        source: vectorSource
    });

    const map = new ol.Map({
        layers: [
            baiduMapLayer,
            iconLayer
        ],
        target: 'map',
        view: new ol.View({
            center: gcoord.transform(centerPoint, gcoord.WGS84, gcoord.BD09MC),
            projection: 'BD:09',
            zoom: 7,
            maxZoom: 18,
            minZoom: 5
            // resolutions
        })
    });

    map.addEventListener('moveend', (evt) => {
        const point = evt.target.getView().getCenter();
        const bd09Point = gcoord.transform(point, gcoord.BD09MC, gcoord.WGS84);
        console.log(point, bd09Point);
    });*/
</script>
</html>